package online.dgyj.led;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.device.GenericConnector;
import com.nle.mylibrary.device.listener.ConnectResultListener;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Handler handler;
    private GenericConnector genericConnector;
    private String ip;
    private int port, address;

    private EditText IPEdit, PortEdit, AddressEdit, editText;
    private Switch RTUSwitch;
    private Button LinkBtn, SendBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        bind();
    }

    private void bind() {
        handler = new Handler(Looper.getMainLooper());

        IPEdit = findViewById(R.id.IPEdit);
        PortEdit = findViewById(R.id.PortEdit);
        AddressEdit = findViewById(R.id.AddressEdit);
        editText = findViewById(R.id.editText);

        RTUSwitch = findViewById(R.id.RTUSwitch);

        LinkBtn = findViewById(R.id.LinkBtn);
        SendBtn = findViewById(R.id.SendBtn);

        LinkBtn.setOnClickListener(this);   // 事件处理
        SendBtn.setOnClickListener(this);   // 事件处理

        RTUSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // 事件处理
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    IPEdit.setHint("SerialName");
                    PortEdit.setHint("Baud");
                    IPEdit.setText("");
                    PortEdit.setText("");
                } else {
                    IPEdit.setHint("IP");
                    PortEdit.setHint("Port");
                    IPEdit.setText("");
                    PortEdit.setText("");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.LinkBtn) {
            if (genericConnector == null) {
                ip = IPEdit.getText().toString();
                port = Integer.parseInt(PortEdit.getText().toString());
                address = Integer.parseInt(AddressEdit.getText().toString());
                if (RTUSwitch.isChecked()) {
                    genericConnector = new GenericConnector(DataBusFactory.newSerialDataBus(Integer.parseInt(ip), port), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("RTU Status", "Link OK");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        IPEdit.setEnabled(false);
                                        RTUSwitch.setEnabled(false);
                                        PortEdit.setEnabled(false);

                                        LinkBtn.setText("DISC");

                                        Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else {
                                Log.e("RTU Status", "Link Error");
                                genericConnector = null;    // 销毁
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                } else {
                    genericConnector = new GenericConnector(DataBusFactory.newSocketDataBus(ip, port), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("TCP Status", "Link OK");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        IPEdit.setEnabled(false);
                                        RTUSwitch.setEnabled(false);
                                        PortEdit.setEnabled(false);

                                        LinkBtn.setText("DISC");

                                        Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else {
                                Log.e("TCP Status", "Link Error");
                                genericConnector = null;    // 销毁
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }
            } else {
                IPEdit.setEnabled(true);
                RTUSwitch.setEnabled(true);
                PortEdit.setEnabled(true);

                LinkBtn.setText("Link");

                Toast.makeText(getApplication(), "断开连接", Toast.LENGTH_SHORT).show();

                // 销毁
                genericConnector.stopConnect();
                genericConnector = null;
            }
        }
        // 发送文字
        else if (v.getId() == R.id.SendBtn) {
            try {
                genericConnector.LedScreenCmd(address,0,0,16,1, String.valueOf(editText.getText()),null);
            } catch (Exception e) {
                Log.e("CMD",e.toString());
            }
        }
        // 重置(疑似失效)
        else if (v.getId() == R.id.ClearBtn) {
            try {
                genericConnector.ClearLedScreen(address,null);
            } catch (Exception e) {
                Log.e("Clear",e.toString());
            }
        }
    }
}